package ilog

import (
	"fmt"

	"gitee.com/mkwchecking/sr-core/yal/ymap"
)

type (
	// install logger func
	InstallLogger func(*Config, Writer) (Logger, error)

	// install logger writer func
	InstallLoggerWriter func(*Config) (Writer, error)
)

var (
	writerRegister = ymap.New[OutType, InstallLoggerWriter]()
	loggerRegister = ymap.NewRegister[InstallLogger]()
)

func RegisterLogHandler(name string, handler InstallLogger) {
	loggerRegister.Register(name, handler)
}

func RegisterLogWriter(name OutType, handler InstallLoggerWriter) {
	writerRegister.Register(name, handler)
}

// Instantiate handler
func InstantiateHandler(name string, cfg *Config, writer Writer) (Logger, error) {
	handler, ok := loggerRegister.Get(name)
	if !ok {
		return nil, fmt.Errorf("log handler '%s' not found", name)
	}
	return handler(cfg, writer)
}

// Instantiate writer
func InstantiateWriter(name OutType, cfg *Config) (Writer, error) {
	handler, ok := writerRegister.Get(name)
	if !ok {
		return nil, fmt.Errorf("log writer %s not found", name)
	}
	return handler(cfg)
}
